<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0%;
            margin: 0%;
        }

        div {
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;

        }
    </style>
</head>

<body>
    <button class="b1">点击到500</button>
    <button class="b2">点击到800</button>
    <div>
        111
    </div>
    <script>
        function animate(obj, target,callback) {
            clearInterval(obj.timer);
            var step = (target - obj.offsetLeft) / 10;
            step>0? Math.ceil(step) : Math.floor(step)
            obj.timer = setInterval(function () {
                if (obj.offsetLeft == target) {
                    clearInterval(obj.timer);
                    if(callback){
                        callback();
                    }
                }
                obj.style.left = obj.offsetLeft + step + 'px';
            }, 30);
        }

        var div = document.querySelector('div');
        var btn500 = document.querySelector('.b1');
        var btn800 = document.querySelector('.b2');


        btn500.addEventListener('click', function () {
            animate(div, 500);
        })
        btn800.addEventListener('click', function () {
            animate(div, 800 ,function(){
                div.style.backgroundColor = 'red';
            });
        })
    </script>
</body>

</html>